<?php

namespace App\Modules\Task\Services;


use App\Modules\Task\Models\Task;
use App\Modules\Index\Services\GlucoseService;
use App\Modules\User\Services\UserService;
use Illuminate\Support\Facades\DB;
use App\Modules\Index\Models\Glucose;
use App\Modules\Task\Models\DrawTask;
use App\Modules\Home\Models\Archives;

class TaskService
{
    //任务code
    public $taskCode = ['qiandao'=>'SIGNIN','kongtang'=>'SUGAR','jiankang'=>'HEALTH'];
    /**
     * 任务列表
     * @param array $data
     * @return mixed
     */
    public static function getList($data=[]) {
        return Task::getList($data);
    }

    /**
     * 获取用户任务列表的领取情况
     */
    public function taskTrait($userData,$data){
        foreach ( $data as $key => $value ) {
//            $data[$key]['is_receive'] = 0;
            $data[$key]['receive_status'] = 0;
            $data[$key]['trait'] = [];
            if ( $value['code'] == $this->taskCode['jiankang'] ) {
                $drawTaskData = DrawTaskService::getHealthDrawTask($value['code'],$userData['id']);
            } else {
                $drawTaskData = DrawTaskService::getDrawTask($value['code'],$userData['id']);
            }
            if ( empty($drawTaskData) ) {
                continue;
            }
//            $data[$key]['is_receive'] = 1;      //是否领取
            $data[$key]['receive_status'] = $drawTaskData->status;  //状态(1进行中 2已完成)
            switch ( $value['code'] ) {
                case $this->taskCode['qiandao']:       //签到任务
                    $start_time = date('Y-m-d').' '.$value['start_time'].':00';
                    $end_time = date('Y-m-d').' '.$value['end_time'].':00';
                    //获取测量数据
                    $glucoseData = GlucoseService::dayGlucose($userData['id'],$start_time,$end_time);    //只获取当天任务时间段的测量数据
                    if ( !empty($glucoseData) ) {
                        $mealsArr = array_merge(array_unique(array_column($glucoseData->toArray(),'meals')));
                        $data[$key]['trait'] = $mealsArr;
                    }
                    break;
                case $this->taskCode['kongtang']:       //控糖达标
                    $start_time = date('Y-m-d').' '.$value['start_time'].':00';
                    $end_time = date('Y-m-d').' '.$value['end_time'].':00';
                    //血糖测量记录（达标率=正常血糖测量次数÷任务时段内总测量次数）
                    $glucoseCount = Glucose::where('user_id',$userData['id'])->where('type',2)->where('test_at','>=',$start_time)->where('test_at','<=',$end_time)->count();
                    $normalCount = Glucose::where('user_id',$userData['id'])->where('type',2)->where('state',1)->where('test_at','>=',$start_time)->where('test_at','<=',$end_time)->count();
                    $successRate = empty($glucoseCount) ? 0 : round($normalCount / $glucoseCount * 100,1);
                    $data[$key]['trait']['success_rate'] = $successRate;
                    $data[$key]['trait']['target_value'] = $userData['target_value'];
                    break;
                case $this->taskCode['jiankang']:   //健康档案

                    break;
                default:
                    $data[$key]['trait'] = [];
                    break;
            }
        }
        return $data;
    }

    /**
     * 任务详情
     */
    public static function getTask($id,$field){
        return Task::getTask($id,$field);
    }

    /**
     * 任务详情
     */
    public static function addTask($data){
        return Task::addTask($data);
    }

    /**
     * 任务详情
     */
    public static function updateTask($data){
        return Task::updateTask($data);
    }


    /**
     * 判断健康档案任务是否完成
     */
    public function archivesTask($user_id,$dataArr){
        //获取健康档案任务id（固定code:HEALTH）
        $code  = $this->taskCode['jiankang'];
        $task = Task::getTask($code,'code');
        if ( empty($task) ) {
            return false;
        }
        $taskId = $task->id;
        $taskCode = $task->code;
        $drawTask = DrawTask::where('user_id',$user_id)->where('task_code',$taskCode)->where('status',2)->first();
        if ( !empty($drawTask) ) {
            return false;
        }
        //获取个人健康档案
        $archivesData = Archives::where('user_id',$user_id)->first();
        if ( empty($archivesData) ) {
            return false;
        }
        //判断是否都填了值
        if ( empty($dataArr->name) || empty($dataArr->gender) || empty($dataArr->birth_at) || empty($dataArr->papers_type) || empty($dataArr->papers) || empty($dataArr->height) || empty($dataArr->weight) || empty($archivesData->dm_age) || empty($archivesData->complication) || empty($archivesData->treatment) ) {
            return false;
        }
        if ( (empty($archivesData->dm_type) && $archivesData->dm_type !== 0) || (empty($archivesData->is_smoke) && $archivesData->is_smoke !== 0) || (empty($archivesData->is_drink) && $archivesData->is_drink !== 0) ) {
            return false;
        }
        $date = date('Y-m-d H:i:s',time());
        //添加完成任务
        $drawTaskCreateArr = [
            'user_id'   => $user_id,
            'task_id'   => $taskId,
            'task_code' => $taskCode,
            'coin'      => $task->coin,
            'created_at'=> $date,
            'updated_at'=> $date,
            'status'    => 2
        ];
        DB::beginTransaction();
        try{
            $drawTaskCreate = DB::table('drawtask')->insertGetId($drawTaskCreateArr);
            if ( empty($drawTaskCreate) ) throw new \Exception('UPDATE_FAILURE');
            //添加金币账单表
            $coinInsertArr = [
                'user_id'       => $user_id,
                'associated_id' => $drawTaskCreate,
                'type'          => 2,
                'created_at'    => $date,
                'updated_at'    => $date,
                'coin'          => $task->coin,
            ];
            $coinInsert = DB::table('coin')->insert($coinInsertArr);
            if ( empty($coinInsert) ) throw new \Exception('UPDATE_FAILURE');
            //修改用户表金币
            $updateUser = UserService::updateCoin($user_id,$task->coin);
            if( empty($updateUser) ) throw new \Exception('UPDATE_FAILURE');
            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            return false;
        }
        return $drawTaskCreate;
    }

    /**
     * 任务 - 签到任务 - 每日3餐前后至少完成一次血糖测量
     */
    public function taskMeasurement($user_id){
        //任务-固定code
        $code  = $this->taskCode['qiandao'];
        //查到任务ID
        $taskData = Task::getTask($code,'code');
        if ( empty($taskData) ) {
            return false;
        }
        $task_code = $taskData->code;
        $start_time = strtotime($taskData->start_time);
        $end_time = strtotime($taskData->end_time);
        //判断任务是否在区间
        $hours = strtotime(date('H:i',time()));
        if ( $hours < $start_time || $hours >= $end_time ) {
            return false;
        }
        //判断当天是否有领取任务
        $drawTaskData = DrawTaskService::getDrawTask($task_code,$user_id);
        if ( empty($drawTaskData) || $drawTaskData->status == 2 ) {
            return false;
        }
        $drawTaskId = $drawTaskData->id;
        //判断是否完成任务
        $start_time = date('Y-m-d').' '.$taskData['start_time'].':00';
        $end_time = date('Y-m-d').' '.$taskData['end_time'].':00';
        $glucoseData = GlucoseService::dayGlucose($user_id,$start_time,$end_time);    //只获取当天任务时间段的测量数据
        if ( empty($glucoseData) ) {
            return false;
        }
        $fixedArr = [1,2,3,4,5,6];  //对应数据表1：早餐前  2：早餐后 3：中餐前 4：中餐后 5：晚餐前 6：晚餐后
        $mealsArr = array_column($glucoseData->toArray(),'meals');
        //交集是否与固定数组一样
        $intersect = array_intersect($mealsArr, $fixedArr);
        sort($intersect);
        if ( $fixedArr != $intersect ) {
            return false;
        }
        $date = date('Y-m-d H:i:s',time());
        DB::beginTransaction();
        try{
            //修改领取任务为已完成
            $updateDrawTask = DrawTaskService::updateDrawTask(['id'=>$drawTaskId,'status'=>2]);
            if( empty($updateDrawTask) ) throw new \Exception('UPDATE_FAILURE');
            //添加金币账单表
            $coinInsertArr = [
                'user_id'       => $user_id,
                'associated_id' => $drawTaskId,
                'type'          => 2,
                'created_at'    => $date,
                'updated_at'    => $date,
                'coin'          => $drawTaskData->coin,
            ];
            $coinInsert = DB::table('coin')->insert($coinInsertArr);
            if ( empty($coinInsert) ) throw new \Exception('UPDATE_FAILURE');
            //修改用户表金币
            $updateUser = UserService::updateCoin($user_id,$drawTaskData->coin);
            if( empty($updateUser) ) throw new \Exception('UPDATE_FAILURE');
            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            return false;
        }
        return true;
    }

    /**
     * 任务头部
     */
    public static function glucoseRate($user_id){
        $dateStart = date('Y-m-d').' 00:00:00';
        $dateEnd = date('Y-m-d').' 23:59:59';
        $glucoseCount = Glucose::where('user_id',$user_id)->where('type',2)->where('test_at','>=',$dateStart)->where('test_at','<=',$dateEnd)->count();
        $normalCount = Glucose::where('user_id',$user_id)->where('type',2)->where('state',1)->where('test_at','>=',$dateStart)->where('test_at','<=',$dateEnd)->count();
        $successRate = empty($glucoseCount) ? 0 : round($normalCount / $glucoseCount * 100,1);
        return ['glucose_count'=>$glucoseCount,'normal_count'=>$normalCount,'success_rate'=>$successRate];
    }

    /**
     * 控糖达标任务-定时任务
     * $taskTimeStatus false直接执行 true按任务时间执行
     */
    public function taskSugar($taskTimeStatus=false){
        $code  = $this->taskCode['kongtang'];
        //查询当天所有领取任务的人员
        $time = date('Y-m-d');
        $startTime = $time.' 00:00:00';
        $endTime = $time.' 23:59:59';
        return DrawTaskService::oneTaskDrawAll($code,$startTime,$endTime,$taskTimeStatus);
    }
}